package com.eunion.web.common.base;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.eunion.core.LogUtil;
import com.eunion.core.PageData;

public class BaseJdbcTemplateHelper {

	@SuppressWarnings("unchecked")
	public void fetchPage(JdbcTemplate jt, StringBuilder sqlCountRows, StringBuilder sqlFetchRows, Object args[], PageData params, final RowMapper rowMapper) {
		if (null == params) params = new PageData();
		params.calculate();
		Integer size = params.getLimit();
		if (null == size || size < PageData.PAGE_SIZE_DEFAULT) {
			size = PageData.PAGE_SIZE_DEFAULT;
		}
		Integer offset = params.getOffset();// offset是最后的数目
		Integer frompage = PageData.DEFAULT_1;
		if (null != offset) {
			frompage = offset / size;
		} else {
			frompage = params.getPageNumber();
		}
		// frompage, size
		// determine how many rows are available
		final List<Map<String, Object>> rowCount = jt.queryForList(sqlFetchRows.toString(), args);
		params.setTotal(rowCount.size());
		params.calculate();
		final List list = new ArrayList();
		if (rowCount.size() > 0) {
			sqlFetchRows.append(" limit " + offset + " , " + params.getLimit());
			LogUtil.get(this.getClass()).debug("PageData int total {} , rows {} ", params.getTotal(), params.getRows());
			jt.query(sqlFetchRows.toString(), args, new ResultSetExtractor() {

				public Object extractData(ResultSet rs)
				    throws SQLException, DataAccessException {
					int currentRow = 0;
					while (rs.next()) {
						list.add(rowMapper.mapRow(rs, currentRow));
						currentRow++ ;
					}
					return list;
				}
			});
		}
		params.setRows(list);
		params.calculate();
	}

}
